package com.param.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import com.param.dto.ParamDataDto;
import com.util.Result;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.cookie.Cookie;
import org.apache.http.client.config.RequestConfig;
import java.nio.charset.StandardCharsets;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
//import org.jsoup.Connection;
//import org.jsoup.Jsoup;
//import org.jsoup.nodes.Document;
import com.alibaba.fastjson.JSONArray;
import com.param.dto.DictDto;
import com.util.JsoupUtils;
import org.apache.http.HttpResponse;

public class ParamUtil {

    public static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
    public static final List<DictDto> dictList = ParamConstants.initDict();

    /**
     * 获取设备2.0通讯模块信息
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAllCommunicationData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 创建HttpClient实例
            HttpGet httpGet = new HttpGet(url); // 创建HttpGet请求
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue()); // 设置cookies
            }

            CloseableHttpResponse response = httpClient.execute(httpGet); // 发送请求并获取响应
            int statusCode = response.getStatusLine().getStatusCode(); // 获取状态码
            if (statusCode == 200) { // 如果状态码为200
                String data = EntityUtils.toString(response.getEntity()); // 获取响应体内容
                System.out.println("===communication===>原始通讯模块信息：" + data);

                JSONObject parse = JSONObject.parseObject(data);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONObject jsonM3g = (JSONObject) jsonMdvr.get("M3G");
                    JSONObject jsonMp = (JSONObject) jsonM3g.get("MP");
                    String jsonApn = jsonMp.getString("APN");

                    map.put("communication-1-1", jsonApn);
                }
            } else {
                System.out.println("HTTP请求失败，状态码: " + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("communication", "error");
        }
        System.out.println("===communication===>解析后通讯模块信息：" + JSONObject.toJSONString(map));

    }

    /**
     * 获取设备1.0通讯模块信息
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAllCommunicationDataV1(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 创建HttpClient实例
            HttpPost httpPost = new HttpPost(url); // 创建HttpPost请求
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置Content-Type

            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue()); // 设置cookies
            }

            Map<String, String> param = new HashMap<>();
            param.put("REQ", ParamConstants.REQ_COMMUNICATION_V1);
            StringEntity entity = new StringEntity(JsoupUtils.mapToString(param), "UTF-8"); // 将参数转换为字符串实体
            httpPost.setEntity(entity); // 设置请求体

            CloseableHttpResponse response = httpClient.execute(httpPost); // 发送请求并获取响应
            int statusCode = response.getStatusLine().getStatusCode(); // 获取状态码
            if (statusCode == 200) { // 如果状态码为200
                String data = EntityUtils.toString(response.getEntity(), "UTF-8"); // 获取响应体内容
                System.out.println("===communication===>原始通讯模块信息：" + data);

                JSONObject parse = JSONObject.parseObject(data);
                JSONObject jsonParam = (JSONObject) parse.get("PARAMETER");
                JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                JSONObject jsonM3g = (JSONObject) jsonMdvr.get("M3G");
                JSONObject jsonMp = (JSONObject) jsonM3g.get("MP");
                String jsonApn = jsonMp.getString("APN");

                map.put("communication-1-1", jsonApn);
            } else {
                System.out.println("HTTP请求失败，状态码: " + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("communication", "error");
        }
        System.out.println("===communication===>解析后通讯模块信息：" + JSONObject.toJSONString(map));

    }


    /**
     * 获取设备2.0AI报警信息
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAlarmData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url); // 创建HttpGet请求
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue()); // 设置cookies
            }

            CloseableHttpResponse response = httpClient.execute(httpGet); // 发送请求并获取响应
            int statusCode = response.getStatusLine().getStatusCode(); // 获取状态码
            if (statusCode == 200) {
                String data = EntityUtils.toString(response.getEntity(), "UTF-8"); // 获取响应体内容
                System.out.println("===alarm===>原始AI报警信息：" + data);

                JSONObject parse = JSONObject.parseObject(data);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    // data-PARAMETER-MDVR-DSM-DSMA-0
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONObject jsonDsm = (JSONObject) jsonMdvr.get("DSM");
                    JSONArray jsonArray = (JSONArray) jsonDsm.get("DSMA");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject one = jsonArray.getJSONObject(i);
                        Integer en = one.getInteger("EN"); // 是否使能 1：是，0：否
                        if (en == 0) {
                            map.put("alarm-" + (i + 1), "off"); // 未启用
                            continue;
                        }
                        // 一级报警范围
                        String min = one.getString("FGMS");
                        String max = one.getString("SGMS");
                        if (i == 1) { // 无驾驶员特殊处理
                            max = "";
                        }
                        map.put("alarm-" + (i + 1) + "-1", min + "#" + max);

                        // 灵敏度
                        map.put("alarm-" + (i + 1) + "-3", resultData((Integer) one.get("ESST"), "alarm-esst")); // 灵敏度

                        // 持续时间
                        String spone = one.getString("SPONE");
                        if (spone != null && spone.length() > 3) {
                            spone = spone.substring(0, 2);
                            map.put("alarm-" + (i + 1) + "-2", spone);
                        } else {
                            // 判断条件
                            map.put("alarm-" + (i + 1) + "-4", resultData((Integer) one.get("SPONE"), "alarm-spone")); // 灵敏度
                        }

                        // 分心范围
                        map.put("alarm-" + (i + 1) + "-5", resultData((Integer) one.get("SPTHREE"), "alarm-spthree")); // 分心程度

                        // 报警有效时间
                        map.put("alarm-" + (i + 1) + "-6", one.getString("SDT")); // 音频编码格式
                    }
                }
            } else {
                System.out.println("HTTP请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            map.put("alarm", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后AI报警信息：" + JSONObject.toJSONString(map));
    }

    /**
     * 获取设备1.0AI报警信息
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAlarmDataV1(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url); // 创建HttpPost请求
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置Content-Type

            // 设置cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            Map<String, String> param = new HashMap<>();
            param.put("REQ", ParamConstants.REQ_ALARM_V1);

            // 将参数转换为字符串并设置到请求体中
            StringEntity params = new StringEntity(JSONObject.toJSONString(param), "UTF-8");
            httpPost.setEntity(params);

            CloseableHttpResponse response = httpClient.execute(httpPost); // 发送请求并获取响应
            int statusCode = response.getStatusLine().getStatusCode(); // 获取状态码
            if (statusCode == 200) {
                String data = EntityUtils.toString(response.getEntity(), "UTF-8"); // 获取响应体内容
                System.out.println("===alarm===>原始AI报警信息：" + data);

                JSONObject parse = JSONObject.parseObject(data);
                JSONObject jsonParam = (JSONObject) parse.get("PARAMETER");
                JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                JSONObject jsonDsm = (JSONObject) jsonMdvr.get("DSM");
                JSONArray jsonArray = (JSONArray) jsonDsm.get("DSMA");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject one = jsonArray.getJSONObject(i);
                    Integer en = one.getInteger("EN"); // 是否使能 1：是，0：否
                    if (en == 0) {
                        map.put("alarm-" + (i + 1), "off"); // 未启用
                        continue;
                    }
                    // 一级报警范围
                    String min = one.getString("FGMS");
                    String max = one.getString("SGMS");
                    if (i == 1) { // 无驾驶员特殊处理
                        max = "";
                    }
                    map.put("alarm-" + (i + 1) + "-1", min + "#" + max);

                    // 灵敏度
                    map.put("alarm-" + (i + 1) + "-3", resultData((Integer) one.get("ESST"), "alarm-esst")); // 灵敏度

                    // 持续时间
                    String spone = one.getString("SPONE");
                    if (spone != null && spone.length() > 3) {
                        spone = spone.substring(0, 2);
                        map.put("alarm-" + (i + 1) + "-2", spone);
                    } else {
                        // 判断条件
                        map.put("alarm-" + (i + 1) + "-4", resultData((Integer) one.get("SPONE"), "alarm-spone")); // 灵敏度
                    }

                    // 分心范围
                    map.put("alarm-" + (i + 1) + "-5", resultData((Integer) one.get("SPTHREE"), "alarm-spthree")); // 分心程度

                    // 报警有效时间
                    map.put("alarm-" + (i + 1) + "-6", one.getString("SDT")); // 音频编码格式
                }
            } else {
                System.out.println("HTTP请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            map.put("alarm", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后AI报警信息：" + JSONObject.toJSONString(map));
    }

    /**
     * 获取设备2.0音频数据
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAudioData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url); // 创建HttpGet请求
            httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置Content-Type

            // 设置cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            CloseableHttpResponse response = httpClient.execute(httpGet); // 发送请求并获取响应
            int statusCode = response.getStatusLine().getStatusCode(); // 获取状态码
            if (statusCode == 200) {
                String data = EntityUtils.toString(response.getEntity(), "UTF-8"); // 获取响应体内容
                System.out.println("===audio===>原始音频信息：" + data);

                JSONObject parse = JSONObject.parseObject(data);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    // data-PARAMETER-MDVR-MAIN-0
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONArray jsonArray = (JSONArray) jsonMdvr.get("MAIN");

                    // 获取音频
                    JSONObject jsonRp = (JSONObject) jsonMdvr.get("RP");
                    JSONArray jsonRcp = (JSONArray) jsonRp.get("RCP");

                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject one = jsonArray.getJSONObject(i);
                        JSONObject oneRcp = jsonRcp.getJSONObject(i);
                        Integer en = one.getInteger("VEN"); // 是否使能 1：是，0：否
                        if (en == 0) {
                            map.put("audio-" + (i + 1), "off"); // 未启用
                            continue;
                        }
                        map.put("audio-" + (i + 1) + "-1", resultData((Integer) one.get("RST"), "audio-rst")); // 分辨率
                        map.put("audio-" + (i + 1) + "-2", resultData((Integer) one.get("FR"), "audio-fr")); // 帧率
                        map.put("audio-" + (i + 1) + "-3", resultData((Integer) one.get("QLT"), "audio-qlt")); // 画质
                        map.put("audio-" + (i + 1) + "-4", resultData((Integer) oneRcp.get("RM"), "audio-rm")); // 录像方式
                        map.put("audio-" + (i + 1) + "-5", resultData((Integer) one.get("AEN"), "audio-aen")); // 录音
                        map.put("audio-" + (i + 1) + "-6", resultData((Integer) one.get("AMT"), "audio-at")); // 音频编码格式
                        if (i > 7) {
                            break;
                        }
                    }
                }
            } else {
                System.out.println("HTTP请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            map.put("audio", "error");
            e.printStackTrace();
        }
        if (map.containsKey("audio") && map.get("audio") != null && "error".equals(map.get("audio"))) {
            System.out.println("===audio===>获取音频2：" + JSONObject.toJSONString(map));
            getAudioData2(cookiesMap, url, map);
        }
    }


    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAudioData2(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        map.remove("audio"); // 移除audio键
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url); // 创建HttpGet请求
            httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置Content-Type

            // 设置cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            CloseableHttpResponse response = httpClient.execute(httpGet); // 发送请求并获取响应
            int statusCode = response.getStatusLine().getStatusCode(); // 获取状态码
            if (statusCode == 200) {
                String data = EntityUtils.toString(response.getEntity(), "UTF-8"); // 获取响应体内容
                JSONObject parse = JSONObject.parseObject(data);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    // data-PARAMETER-MDVR-MAIN-0
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONArray jsonArray = (JSONArray) jsonMdvr.get("MAIN");

                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject one = jsonArray.getJSONObject(i);
                        Integer en = one.getInteger("VEN"); // 是否使能 1：是，0：否
                        if (en == 0) {
                            map.put("audio-" + (i + 1), "off"); // 未启用
                            continue;
                        }
                        map.put("audio-" + (i + 1) + "-1", resultData((Integer) one.get("RST"), "audio-rst")); // 分辨率
                        map.put("audio-" + (i + 1) + "-2", resultData((Integer) one.get("FR"), "audio-fr")); // 帧率
                        map.put("audio-" + (i + 1) + "-3", "1"); // 画质
                        map.put("audio-" + (i + 1) + "-4", "开机录像"); // 录像方式
                        map.put("audio-" + (i + 1) + "-5", "录音"); // 录音
                        map.put("audio-" + (i + 1) + "-6", "G711A"); // 音频编码格式
                        if (i > 7) {
                            break;
                        }
                    }
                }
            } else {
                System.out.println("HTTP请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            map.put("audio", "error");
            e.printStackTrace();
        }
        System.out.println("===audio===>获取音频2结果：" + JSONObject.toJSONString(map));
    }


    /**
     * 获取设备1.0音频数据
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAudioDataV1(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url); // 创建HttpPost请求
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置Content-Type

            // 设置cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.addHeader("Cookie", entry.getKey() + "=" + entry.getValue());
            }

            // 构建参数
            Map<String, String> param = new HashMap<>();
            param.put("REQ", ParamConstants.REQ_AUDIO_V1);
            StringEntity entity = new StringEntity(toUrlEncodedForm(param), "UTF-8");
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost); // 发送请求并获取响应
            int statusCode = response.getStatusLine().getStatusCode(); // 获取状态码
            if (statusCode == 200) {
                String data = EntityUtils.toString(response.getEntity(), "UTF-8"); // 获取响应体内容
                System.out.println("===audio===>原始音频信息：" + data);
                JSONObject parse = JSONObject.parseObject(data);
                JSONObject jsonParam = (JSONObject) parse.get("PARAMETER");
                JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                JSONArray jsonArray = (JSONArray) jsonMdvr.get("MAIN");

                // 获取音频
                JSONObject jsonRp = (JSONObject) jsonMdvr.get("RP");
                JSONArray jsonRcp = (JSONArray) jsonRp.get("RCP");

                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject one = jsonArray.getJSONObject(i);
                    JSONObject oneRcp = jsonRcp.getJSONObject(i);
                    Integer en = one.getInteger("VEN"); // 是否使能 1：是，0：否
                    if (en == 0) {
                        map.put("audio-" + (i + 1), "off"); // 未启用
                        continue;
                    }
                    map.put("audio-" + (i + 1) + "-1", resultData((Integer) one.get("RST"), "audio-rst")); // 分辨率
                    map.put("audio-" + (i + 1) + "-2", resultData((Integer) one.get("FR"), "audio-fr")); // 帧率
                    map.put("audio-" + (i + 1) + "-3", resultData((Integer) one.get("QLT"), "audio-qlt")); // 画质
                    map.put("audio-" + (i + 1) + "-4", resultData((Integer) oneRcp.get("RM"), "audio-rm")); // 录像方式
                    map.put("audio-" + (i + 1) + "-5", resultData((Integer) one.get("AEN"), "audio-aen")); // 录音
                    map.put("audio-" + (i + 1) + "-6", resultData((Integer) one.get("AMT"), "audio-at")); // 音频编码格式
                    map.put("audio-" + (i + 1) + "-7", resultData((Integer) one.get("RAG"), "rotation-angle")); // 旋转角度
                    if (i > 7) {
                        break;
                    }
                }
            } else {
                System.out.println("HTTP请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            map.put("audio", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后音频信息：" + JSONObject.toJSONString(map));
    }

    /**
     * 辅助方法，用于将Map转换为URL编码的字符串形式
     *
     * @author yulian174
     */
    private static String toUrlEncodedForm(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return sb.toString();
    }


    /**
     * 获取设备2.0串口报警数据
     * @param cookiesMap
     * @param url
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getPortAlarmData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try {
            // 使用 HttpURLConnection 替换原有的 Jsoup 连接
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法
            con.setRequestMethod("GET");

            // 设置请求头
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                con.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // 发送请求并获取响应
            int responseCode = con.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();

                // 解析 HTML 字符串
                String data = content.toString();
                System.out.println("===portalarm===>原始串口报警信息：" + data);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(data);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    //data-PARAMETER-MDVR-IOP-0
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONArray jsonArray = (JSONArray) jsonMdvr.get("IOP");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject one = jsonArray.getJSONObject(i);
                        Integer en = one.getInteger("EN");
                        if (en == 0) {
                            map.put("portalarm-" + (i + 1), "off"); // 未启用
                            continue;
                        }
                        //map.put("portalarm-"+(i+1)+"-1", resultData((Integer) one.get("TM"),"portalarm-tm"));
                        map.put("portalarm-" + (i + 1) + "-2", resultData((Integer) one.get("EL"), "portalarm-el"));
                        map.put("portalarm-" + (i + 1) + "-3", one.get("SDT"));
                        if (i > 7) {
                            break;
                        }
                    }
                }
            } else {
                throw new Exception("HTTP error code: " + responseCode);
            }
        } catch (Exception e) {
            map.put("portalarm", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后串口报警信息：" + JSONObject.toJSONString(map));
    }

    /**
     * 获取设备1.0串口报警数据
     * @param cookiesMap
     * @param url
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getPortAlarmDataV1(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置请求参数
            Map<String, String> param = new HashMap<>();
            param.put("REQ", ParamConstants.REQ_PORTALARM_V1);

            // 将参数转换为字符串
            StringBuilder paramStrBuilder = new StringBuilder();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                if (paramStrBuilder.length() > 0) {
                    paramStrBuilder.append("&");
                }
                paramStrBuilder.append(entry.getKey()).append("=").append(entry.getValue());
            }

            // 设置参数实体
            httpPost.setEntity(new StringEntity(paramStrBuilder.toString(), StandardCharsets.UTF_8));

            // 设置 cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                System.out.println("===portalarm===>原始串口报警信息：" + data);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(data);
                JSONObject jsonParam = (JSONObject) parse.get("PARAMETER");
                JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                JSONArray jsonArray = (JSONArray) jsonMdvr.get("IOP");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject one = jsonArray.getJSONObject(i);
                    Integer en = one.getInteger("EN");
                    if (en == 0) {
                        map.put("portalarm-" + (i + 1), "off"); // 未启用
                        continue;
                    }
                    //map.put("portalarm-"+(i+1)+"-1", resultData((Integer) one.get("TM"),"portalarm-tm"));
                    map.put("portalarm-" + (i + 1) + "-2", resultData((Integer) one.get("EL"), "portalarm-el"));
                    map.put("portalarm-" + (i + 1) + "-3", one.get("SDT"));
                    if (i > 7) {
                        break;
                    }
                }
            } else {
                throw new IOException("HTTP error code: " + statusCode);
            }
        } catch (IOException e) {
            map.put("portalarm", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后串口报警信息：" + JSONObject.toJSONString(map));
    }


    /**
     * 获取设备2.0串口数据
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getPortData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            // 设置 cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                Logger.getGlobal().info("===port===>原始串口信息：" + data);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(data);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONObject jsonPSS = (JSONObject) jsonMdvr.get("PSS");
                    JSONArray jsonArray = (JSONArray) jsonPSS.get("SP");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject serverOne = jsonArray.getJSONObject(i);
                        //data-PARAMETER-MDVR-PSS-SP-0-FT
                        if ((Integer) serverOne.get("FT") == 2) { // 串口-外设特殊情况
                            Integer st = (Integer) serverOne.get("ST");
                            if (st == 0) {
                                map.put("port-" + (i + 1) + "-1", "控制面板");
                            } else if (st == 1) {
                                map.put("port-" + (i + 1) + "-1", "老控制面板");
                            }
                        } else {
                            map.put("port-" + (i + 1) + "-1", resultData((Integer) serverOne.get("FT"), "port-ft")); // 外设
                        }
                        //data-PARAMETER-MDVR-PSS-SP-0-BR
                        map.put("port-" + (i + 1) + "-2", resultData((Integer) serverOne.get("BR"), "port-br")); // 波特率
                        if (i > 3) {
                            break;
                        }
                    }
                }
            } else {
                throw new IOException("HTTP error code: " + statusCode);
            }
        } catch (IOException e) {
            map.put("port", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后串口信息：" + JSONObject.toJSONString(map));
    }

    /**
     * 获取设备1.0串口数据
     * @param cookiesMap
     * @param url
     * @param map
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getPortDataV1(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置 cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 构造请求参数
            Map<String, String> param = new HashMap<>();
            param.put("REQ", ParamConstants.REQ_PORT_V1);
            String params = toQueryString(param); // 将参数转换为 URL 编码的字符串

            // 设置请求体
            httpPost.setEntity(new StringEntity(params, StandardCharsets.UTF_8));

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                Logger.getGlobal().info("===port===>原始串口信息：" + data);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(data);

                JSONObject jsonParam = (JSONObject) parse.get("PARAMETER");
                JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                JSONObject jsonPSS = (JSONObject) jsonMdvr.get("PSS");
                JSONArray jsonArray = (JSONArray) jsonPSS.get("SP");
                // 设备1.0 索引位置非标准 232-1 对应0 4851对应 4
                JSONObject serverOne = jsonArray.getJSONObject(0);

                if ((Integer) serverOne.get("FT") == 2) { // 串口-外设特殊情况
                    Integer st = (Integer) serverOne.get("ST");
                    if (st == 0) {
                        map.put("port-" + 1 + "-1", "控制面板");
                    } else if (st == 1) {
                        map.put("port-" + 1 + "-1", "老控制面板");
                    }
                } else {
                    map.put("port-" + 1 + "-1", resultData((Integer) serverOne.get("FT"), "port-ft")); // 外设
                }
                map.put("port-" + 1 + "-2", resultData((Integer) serverOne.get("BR"), "port-br")); // 波特率

                JSONObject serverTwo = jsonArray.getJSONObject(4);
                if ((Integer) serverTwo.get("FT") == 2) { // 串口-外设特殊情况
                    Integer st = (Integer) serverTwo.get("ST");
                    if (st == 0) {
                        map.put("port-" + 2 + "-1", "控制面板");
                    } else if (st == 1) {
                        map.put("port-" + 2 + "-1", "老控制面板");
                    }
                } else {
                    map.put("port-" + 2 + "-1", resultData((Integer) serverTwo.get("FT"), "port-ft")); // 外设
                }
                map.put("port-" + 2 + "-2", resultData((Integer) serverTwo.get("BR"), "port-br")); // 波特率
            } else {
                throw new IOException("HTTP error code: " + statusCode);
            }
        } catch (IOException e) {
            map.put("port", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后串口信息：" + JSONObject.toJSONString(map));
    }

    /**
     * 辅助方法：将 Map 转换为 URL 编码的字符串
     * @author yulian174
     */
    private static String toQueryString(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            sb.append("=");
            sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return sb.toString();
    }

    /**
     * 获取服务器参数信息
     * @param cookiesMap
     * @param systemUrl
     * @param map
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getServerData(Map<String, String> cookiesMap, String systemUrl, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(systemUrl);

            // 设置 cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String sysmData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                System.out.println("===server===>原始设备信息：" + sysmData);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(sysmData);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONObject jsonMCMS = (JSONObject) jsonMdvr.get("MCMS");
                    JSONArray jsonArray = (JSONArray) jsonMCMS.get("SP");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject serverOne = jsonArray.getJSONObject(i);
                        Integer en = serverOne.getInteger("EN");
                        if (en == 0) {
                            map.put("server-" + (i + 1), "off"); // 未启用
                            continue;
                        }
                        if (i > 5) break;
                        map.put("server-" + (i + 1) + "-1", resultData((Integer) serverOne.get("CP"), "server-cp")); // 协议类型
                        map.put("server-" + (i + 1) + "-2", resultData((Integer) serverOne.get("NWT"), "server-nwt"));
                        map.put("server-" + (i + 1) + "-3", serverOne.get("CS"));
                        map.put("server-" + (i + 1) + "-4", serverOne.get("CPORT"));
                        map.put("server-" + (i + 1) + "-5", serverOne.get("MS"));
                        map.put("server-" + (i + 1) + "-6", serverOne.get("MPORT"));
                    }
                }
            } else {
                throw new IOException("HTTP error code: " + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            map.put("server", "error");
        }
        System.out.println("===server===>解析后服务器信息：" + JSONObject.toJSONString(map));
    }

    /**
     * 获取设备1.0服务器参数信息
     * @param cookiesMap
     * @param systemUrl
     * @param map
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getServerDataV1(Map<String, String> cookiesMap, String systemUrl, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(systemUrl);

            // 设置 headers
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置 cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            // 设置请求体
            Map<String, String> param = new HashMap<>();
            param.put("REQ", ParamConstants.REQ_SERVER_V1);
            StringEntity entity = new StringEntity(toQueryStringOne(param), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String sysmData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                System.out.println("===server===>原始设备信息：" + sysmData);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(sysmData);

                JSONObject jsonParam = (JSONObject) parse.get("PARAMETER");
                JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                JSONObject jsonMCMS = (JSONObject) jsonMdvr.get("MCMS");
                JSONArray jsonArray = (JSONArray) jsonMCMS.get("SP");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject serverOne = jsonArray.getJSONObject(i);
                    Integer en = serverOne.getInteger("EN");
                    if (en == 0) {
                        map.put("server-" + (i + 1), "off"); // 未启用
                        continue;
                    }
                    if (i > 5) break;
                    map.put("server-" + (i + 1) + "-1", resultData((Integer) serverOne.get("CP"), "server-cp")); // 协议类型
                    map.put("server-" + (i + 1) + "-2", resultData((Integer) serverOne.get("NWT"), "server-nwt"));
                    map.put("server-" + (i + 1) + "-3", serverOne.get("CS"));
                    map.put("server-" + (i + 1) + "-4", serverOne.get("CPORT"));
                    map.put("server-" + (i + 1) + "-5", serverOne.get("MS"));
                    map.put("server-" + (i + 1) + "-6", serverOne.get("MPORT"));
                }
            } else {
                throw new IOException("HTTP error code: " + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            map.put("server", "error");
        }
        System.out.println("===server===>解析后设备信息：" + JSONObject.toJSONString(map));
    }
    /**
     * 辅助方法，用于构建查询字符串
     * @author yulian174
     */
    private static String toQueryStringOne(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return sb.toString();
    }

    /**
     * 获取设备2.0制式参数信息
     * @param cookiesMap
     * @param url
     * @param map
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAudioZsData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            // 设置 cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                System.out.println("===other===>原始制式参数信息：" + data);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(data);
                Integer status = parse.getInteger("errorcode");
                if (status == 200) {
                    //data-PARAMETER-MDVR-MAIN-0
                    JSONObject jsonData = (JSONObject) parse.get("data");
                    JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                    JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                    JSONObject jsonGSP = (JSONObject) jsonMdvr.get("GSP");
                    Integer vsa = jsonGSP.getInteger("VSA");
                    if (vsa == 0) {
                        map.put("other-1-1", "PAL");
                    } else if (vsa == 1) {
                        map.put("other-1-1", "NTSC");
                    }
                }
            } else {
                throw new IOException("HTTP error code: " + statusCode);
            }
        } catch (IOException e) {
            map.put("other", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后制式参数信息：" + JSONObject.toJSONString(map));
    }


    /**
     * 获取设备1.0制式参数信息
     * @param cookiesMap
     * @param url
     * @param map
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getAudioZsDataV1(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置 headers
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置 cookies
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            // 设置请求体
            Map<String, String> param = new HashMap<>();
            param.put("REQ", ParamConstants.REQ_STANDARD_V1);
            String formUrlEncodedString = toQueryString(param); // 自定义方法
            StringEntity entity = new StringEntity(formUrlEncodedString, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取响应内容
                String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                System.out.println("===other===>原始制式参数信息：" + data);

                // 使用 JSONObject 解析 JSON 数据
                JSONObject parse = JSONObject.parseObject(data);
                JSONObject jsonParam = (JSONObject) parse.get("PARAMETER");
                JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                JSONObject jsonGSP = (JSONObject) jsonMdvr.get("GSP");
                Integer vsa = jsonGSP.getInteger("VSA");
                if (vsa == 0) {
                    map.put("other-1-1", "PAL");
                } else if (vsa == 1) {
                    map.put("other-1-1", "NTSC");
                }
            } else {
                throw new IOException("HTTP error code: " + statusCode);
            }
        } catch (IOException e) {
            map.put("other", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后制式参数信息：" + JSONObject.toJSONString(map));
    }


    /**
     * 获取设备智能应用参数信息
     * @param cookiesMap
     * @param url
     * @param map
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getIntelligenceData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(createCookieStore(cookiesMap))
                .build()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpPost.setConfig(requestConfig);

            // 发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                        System.out.println("===intelligence===>原始智能应用参数信息：" + data);
                        JSONObject parse = JSONObject.parseObject(data);
                        Integer status = parse.getInteger("errorcode");
                        if (status == 200) {
                            JSONObject jsonData = (JSONObject) parse.get("data");
                            JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                            System.out.println("===PARAMETER===>原始智能应用参数信息：" + jsonParam);
                            JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                            System.out.println("===MDVR===>原始智能应用参数信息：" + jsonMdvr);
                            JSONObject jsonIAP = (JSONObject) jsonMdvr.get("IAP");

                            JSONObject jsonGsp = (JSONObject) jsonMdvr.get("GSP");
                            System.out.println("===GSP===>原始智能应用参数尺寸信息：" + jsonGsp);
                            Integer jsonclu = 0;
                            if (null != jsonGsp) {
                                jsonclu = jsonGsp.getInteger("CLU");
                            }
                            System.out.println("===CLU===>原始智能应用参数尺寸信息：" + jsonclu);

                            Integer sih = jsonIAP.getInteger("SIH");
                            Integer adln = jsonIAP.getInteger("ADLN");
                            Integer vwth = jsonIAP.getInteger("VWTH");
                            Integer lrr = jsonIAP.getInteger("LRR");
                            Integer adbh = jsonIAP.getInteger("ADBH");

                            JSONObject jsonDSM = (JSONObject) jsonMdvr.get("DSM");
                            Integer bfm = jsonDSM.getInteger("BFM");

                            if (jsonclu == 0) {
                                map.put("intelligence-1-1", "厘米");
                                map.put("intelligence-1-2", sih);
                                map.put("intelligence-1-3", adln);
                                map.put("intelligence-1-4", vwth);
                                map.put("intelligence-1-5", adbh);
                            } else if (jsonclu == 1) {
                                // 转换比率 2.54  10cm / 2.54 = 3.9英寸
                                double inchValue = 2.54;
                                map.put("intelligence-1-1", "英寸");
                                map.put("intelligence-1-2", Math.round(sih.doubleValue() / inchValue));
                                map.put("intelligence-1-3", Math.round(adln.doubleValue() / inchValue));
                                map.put("intelligence-1-4", Math.round(vwth.doubleValue() / inchValue));
                                map.put("intelligence-1-5", Math.round(adbh.doubleValue() / inchValue));
                            } else {
                                map.put("intelligence", "error");
                            }

                            if (lrr == 0) {
                                map.put("intelligence-1-6", "左舵");
                            } else if (lrr == 1) {
                                map.put("intelligence-1-6", "右舵");
                            } else {
                                map.put("intelligence", "error");
                            }

                            if (bfm == 0) {
                                map.put("intelligence-1-7", "模式1");
                            } else {
                                map.put("intelligence", "error");
                            }
                        }
                    }
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            map.put("intelligence", "error");
            e.printStackTrace();
        }
        if (map.containsKey("intelligence") && map.get("intelligence") != null && "error".equals(map.get("intelligence"))) {
            System.out.println("===intelligence2===>获取智能参数方式2：" + JSONObject.toJSONString(map));
            getIntelligenceDataMethod2(cookiesMap, url, map);
        }
    }
    /**
     * 创建 CookieStore
     * @author yulian174
     */
    private static org.apache.http.client.CookieStore createCookieStore(Map<String, String> cookiesMap) {
        org.apache.http.client.CookieStore cookieStore = new org.apache.http.impl.client.BasicCookieStore();
        for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
            Cookie cookie = new BasicClientCookie(entry.getKey(), entry.getValue());
            cookieStore.addCookie(cookie);
        }
        return cookieStore;
    }

    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getIntelligenceDataMethod2(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(createCookieStore(cookiesMap))
                .build()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpPost.setConfig(requestConfig);

            // 发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                        System.out.println("===intelligence===>原始智能应用参数信息：" + data);
                        JSONObject parse = JSONObject.parseObject(data);
                        Integer status = parse.getInteger("errorcode");
                        if (status == 200) {
                            JSONObject jsonData = (JSONObject) parse.get("data");
                            JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                            System.out.println("===PARAMETER===>原始智能应用参数信息：" + jsonParam);
                            JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                            System.out.println("===MDVR===>原始智能应用参数信息：" + jsonMdvr);
                            JSONObject jsonIAP = (JSONObject) jsonMdvr.get("IAP");

                            Integer jsonclu = 0;
                            jsonclu = jsonIAP.getInteger("IHU");
                            System.out.println("===CLU===>原始智能应用参数尺寸信息：" + jsonclu);

                            Integer sih = jsonIAP.getInteger("SIH");
                            Integer adln = jsonIAP.getInteger("ADLN");
                            Integer vwth = jsonIAP.getInteger("VWTH");
                            Integer adbh = jsonIAP.getInteger("ADBH");

                            if (jsonclu == 0) {
                                map.put("intelligence-1-1", "厘米");
                                map.put("intelligence-1-2", sih);
                                map.put("intelligence-1-3", adln);
                                map.put("intelligence-1-4", vwth);
                                map.put("intelligence-1-5", adbh);
                            } else if (jsonclu == 1) {
                                // 转换比率 2.54  10cm / 2.54 = 3.9英寸
                                double inchValue = 2.54;
                                map.put("intelligence-1-1", "英寸");
                                map.put("intelligence-1-2", Math.round(sih.doubleValue() / inchValue));
                                map.put("intelligence-1-3", Math.round(adln.doubleValue() / inchValue));
                                map.put("intelligence-1-4", Math.round(vwth.doubleValue() / inchValue));
                                map.put("intelligence-1-5", Math.round(adbh.doubleValue() / inchValue));
                            } else {
                                map.put("intelligence", "error");
                            }

                            // 默认设置左舵和模式1
                            map.put("intelligence-1-6", "左舵");
                            map.put("intelligence-1-7", "模式1");
                        }
                    }
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            map.put("intelligence", "error");
            e.printStackTrace();
        }
    }

    /**
     * 获取注册信息出场序列号信息
     * @param cookiesMap
     * @param url
     * @param map
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getRegistrationData(Map<String, String> cookiesMap, String url, Map<String, Object> map, List<ParamDataDto> array) {
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(createCookieStore(cookiesMap))
                .build()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpPost.setConfig(requestConfig);

            // 发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                        System.out.println("===registration===>出厂序列号信息：" + data);
                        JSONObject parse = JSONObject.parseObject(data);
                        Integer status = parse.getInteger("errorcode");
                        if (status == 200) {
                            JSONObject jsonData = (JSONObject) parse.get("data");
                            map.put("registration-1-1", jsonData.get("securitynum"));
                            for (ParamDataDto pdd : array) {
                                if (pdd.getCode().equals("registration-1")) {
                                    for (ParamDataDto pdds : pdd.getChilds()) {
                                        if (pdds.getCode().equals("registration-1-1")) {
                                            pdds.setValue(jsonData.getString("securitynum"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            map.put("registration", "error");
            e.printStackTrace();
        }
        System.out.println("===registration===>解析后注册信息出厂序列号：" + JSONObject.toJSONString(map));
    }

    /**
     * 获取设备有线网络MAC地址信息
     * @param cookiesMap
     * @param url
     * @param map
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static void getWireMacData(Map<String, String> cookiesMap, String url, Map<String, Object> map) {
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(createCookieStore(cookiesMap))
                .build()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpPost.setConfig(requestConfig);

            // 发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                        System.out.println("===wiremac===>MAC信息：" + data);
                        JSONObject parse = JSONObject.parseObject(data);
                        Integer status = parse.getInteger("errorcode");
                        if (status == 200) {
                            JSONObject jsonData = (JSONObject) parse.get("data");
                            JSONObject jsonParam = (JSONObject) jsonData.get("PARAMETER");
                            System.out.println("===PARAMETER===>MAC信息：" + jsonParam);
                            JSONObject jsonMdvr = (JSONObject) jsonParam.get("MDVR");
                            System.out.println("===MDVR===>MAC信息：" + jsonMdvr);
                            JSONObject jsonIAP = (JSONObject) jsonMdvr.get("KEYS");
                            map.put("wirednetwork-1-1", jsonIAP.getString("MAC") == null ? null : jsonIAP.getString("MAC").toUpperCase());
                        }
                    }
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            map.put("wirednetwork", "error");
            e.printStackTrace();
        }
        System.out.println("===server===>解析后有线网络mac信息：" + JSONObject.toJSONString(map));
    }

    public static String resultData(Integer code, String type) {
        List<DictDto> nowList = dictList.stream().filter(e -> e.getType().equals(type)).collect(Collectors.toList());
        if (nowList == null || nowList.isEmpty()) return "参数字典类型未定义";
        DictDto dictDto = nowList.get(0);
        Map<Integer, Object> oneMap = dictDto.getMap();
        if (oneMap.get(code) == null) return "未知";
        return (String) oneMap.get(code);
    }

    /**
     * 获取设备2.0登录的cookie等信息
     * @param loginUrl
     * @param userCode
     * @param passWord
     * @return
     * @throws IOException
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static Map<String, String> getCookiesMap(String loginUrl, String userCode, String passWord, Integer language, Integer autoLogin) {
        Map<String, String> map = new HashMap<>();
        if (userCode == null) {
            userCode = "";
        }
        if (passWord == null) {
            passWord = "";
        }
        map.put("username", userCode);
        map.put("password", passWord);
        if (language != null) {
            map.put("language", String.valueOf(language));
        }
        if (autoLogin != null) {
            map.put("autoLogin", String.valueOf(autoLogin));
        }
        System.out.println("参数比对 loginUrl：" + loginUrl);
        System.out.println("账号密码信息： " + JSONObject.toJSONString(map));

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            System.out.println("获取cookie... ");
            HttpPost httpPost = new HttpPost(loginUrl);
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map), "UTF-8"));

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpPost.setConfig(requestConfig);

            // 发送请求
            HttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    System.out.println("等待cookie返回... ");

                    // 提取 Cookies
                    Map<String, String> cookies = extractCookies(response);
                    return cookies;
                }
            } finally {
                response.getEntity().getContent().close();
            }
        } catch (IOException e) {
            System.out.println("登录异常");
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 提取 Cookies
     * @author yulian174
     */
    private static Map<String, String> extractCookies(HttpResponse response) {
        Map<String, String> cookies = new HashMap<>();
        for (Header header : response.getAllHeaders()) {
            if ("Set-Cookie".equalsIgnoreCase(header.getName())) {
                String value = header.getValue();
                int index = value.indexOf('=');
                if (index > 0) {
                    String key = value.substring(0, index).trim();
                    int end = value.indexOf(';');
                    String val = value.substring(index + 1, end > 0 ? end : value.length()).trim();
                    cookies.put(key, val);
                }
            }
        }
        return cookies;
    }

    /**
     * 获取设备1.0登录的cookie等信息
     * @param loginUrl
     * @param userCode
     * @param passWord
     * @return
     * @throws IOException
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static Map<String, String> getCookiesMapV1(String loginUrl, String userCode, String passWord, Integer language, Integer autoLogin) {
        Map<String, String> map = new HashMap<>();
        if (userCode == null) {
            userCode = "";
        }
        if (passWord == null) {
            passWord = "";
        }
        map.put("username", userCode);
        map.put("userpwd", passWord);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            System.out.println("获取cookie... ");
            HttpPost httpPost = new HttpPost(loginUrl);
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(map), "UTF-8"));

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpPost.setConfig(requestConfig);

            // 发送请求
            HttpResponse response = httpClient.execute(httpPost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    System.out.println("等待cookie返回... ");

                    // 提取 Cookies
                    Map<String, String> cookies = extractCookies(response);
                    return cookies;
                }
            } finally {
                EntityUtils.consume(response.getEntity());
            }
        } catch (IOException e) {
            System.out.println("登录异常");
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 格式化所有存储器
     * @param cookiesMap
     * @param devUrl
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static List<String> getDevsInfo(Map<String, String> cookiesMap, String devUrl) {
        List<String> result = new ArrayList<>();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(devUrl);
            httpGet.setHeader("User-Agent", USER_AGENT);

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpGet.setConfig(requestConfig);

            // 创建 HttpClientContext 并设置 Cookies
            HttpClientContext context = HttpClientContext.create();
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                BasicClientCookie cookie = new BasicClientCookie(entry.getKey(), entry.getValue());
                context.getCookieStore().addCookie(cookie);
            }

            // 发送请求
            HttpResponse response = httpClient.execute(httpGet, context);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    String sysmData = EntityUtils.toString(response.getEntity(), "UTF-8");
                    JSONObject parse = JSONObject.parseObject(sysmData);
                    Integer status = parse.getInteger("errorcode");
                    if (status == 200) {
                        JSONObject jsonData = (JSONObject) parse.get("data");
                        JSONArray jsonArray = (JSONArray) jsonData.get("info");
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject serverOne = jsonArray.getJSONObject(i);
                            System.out.println(serverOne);
                            if (!serverOne.getString("devName").equals("") && !serverOne.getString("devType").equals("0")) {
                                System.out.println("===DEV===>存储器信息：" + serverOne);
                                result.add(serverOne.getString("devId"));
                            }
                        }
                    }
                }
            } finally {
                EntityUtils.consume(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("设备查询完毕: " + result.toString());
        return result;
    }

    /**
     * 格式化所有存储器
     * @param cookiesMap
     * @param formatProcessUrl
     * @return
     */
    /**
     * @author yulian174
     * 修改为 httpclient
     */
    public static Result<String> formatAllDev(Map<String, String> cookiesMap, String formatProcessUrl, List<String> devs) {
        Result<String> result = new Result<>();
        String resutlCount = null;
        String state = null;
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(formatProcessUrl);
            httpGet.setHeader("User-Agent", USER_AGENT);

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                    .build();
            httpGet.setConfig(requestConfig);

            // 创建 HttpClientContext 并设置 Cookies
            HttpClientContext context = HttpClientContext.create();
            for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
                BasicClientCookie cookie = new BasicClientCookie(entry.getKey(), entry.getValue());
                context.getCookieStore().addCookie(cookie);
            }

            // 发送请求
            HttpResponse response = httpClient.execute(httpGet, context);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    String sysmData = EntityUtils.toString(response.getEntity(), "UTF-8");
                    JSONObject parse = JSONObject.parseObject(sysmData);
                    Integer status = parse.getInteger("errorcode");
                    System.out.println("格式化中===》》" + parse.toJSONString());
                    if (status == 200) {
                        JSONObject jsonData = (JSONObject) parse.get("data");
                        System.out.println(jsonData);
                        resutlCount = jsonData.getString("result");
                        state = jsonData.getString("state");
                    } else {
                        result.setMsg("errorcode:" + status);
                        result.setCode(0);
                        return result;
                    }
                }
            } finally {
                EntityUtils.consume(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("格式化结果判定state= resutlCount===》》" + state + "=" + resutlCount);
        if (state.equals("0") && resutlCount.equals(devs.size() + "")) {
            result.setCode(1);
        } else {
            result.setCode(0);
        }
        return result;
    }

}
